package com.hua.api.core.util.tree;

import com.hua.api.core.util.StringUtil;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 方法描述：TODO 树形数据结构构建
 *
 * @auther luoyouhua
 * @version 1.0
 * @datetime 2020-04-07 17:30:29
 * Copyright © 2019 哇棒技术 All Rights Reserved
 */
public class TreeUtil<T extends TreeNode> {


    public static TreeUtil newInstance(){
        return new TreeUtil();
    }

    public  TreeNode<T> node(T data){
        return  new TreeNode<>(data.getCode(),data.getPcode(),data);
    }

    public  List<TreeNode<T>> map(List<T> list){
       return list.stream().map(e ->node(e)).collect(Collectors.toList());
    }


    public TreeNode<T> build(List<T> list,T root){
        List<TreeNode<T>> nodes = map(list);
        TreeNode<T> rootNodes = node(root);
        rootNodes = buildTree(nodes,rootNodes);
        return rootNodes;
    }

    /**
     * 方法描述：TODO 构建数
     *
     * @auther luoyouhua
     * @version 1.0
     * @datetime 2020-04-07 17:37:16
     * Copyright © 2019 哇棒技术 All Rights Reserved
     */
    public TreeNode<T> buildTree(List<TreeNode<T>> datas,TreeNode<T> root){
        List<TreeNode<T>> childs = datas.stream().filter(e -> StringUtil.equals(e.getPcode(),root.getCode())).collect(Collectors.toList());
        if(childs.size()>0){
            childs.stream().map(e->buildTree(datas,e)).collect(Collectors.toList());
        }
        root.setList(childs);

        return root;
    }

    public TreeNode<T> findNode(TreeNode<T> node, String code){
        if(StringUtil.equals(node.getCode(),code)){
            return node;
        }else{
            for(TreeNode nodes:node.getList()){
                TreeNode<T> n = findNode(nodes,code);
                if(null!=n){
                    return n;
                }
            }
        }
        return null;
    }

    /**
     * 方法描述：TODO 查找兄弟节点
     * @auther luoyouhua
     * @version 1.0
     * @datetime 2020-04-08 13:59:30
     * Copyright © 2019 哇棒技术 All Rights Reserved
     */
    public List<TreeNode<T>> findSiblings(TreeNode<T> node,String pcode){
        TreeNode<T> parent = findNode(node,pcode);
        if(null!=parent){
            return parent.getList();
        }
        return null;
    }


}
